<?php
namespace Intendant\Controller;
use Think\Controller;
use Think\Db;
use Hema\Database;
class SiteController extends AuthController {
	public function menu()
	{
		if(S('AuthMenu')){
			$menu = S('AuthMenu');
		}else{
			$menu = M('AuthRule')->select();
			S('AuthMenu',$menu,C('AUTH_MENU_TIME'));
		}
		$this->menu = recursive($menu);
		$this->display();
	}
	// 添加菜单
	public function addMenu()
	{
		$parentid = I('parentid');
		$parentid = $parentid != '' ? $parentid : 0;
		if(S('AuthMenu')){
			$menu = S('AuthMenu');
		}else{
			$menu = M('AuthRule')->select();
			S('AuthMenu',$menu,C('AUTH_MENU_TIME'));
		}
		$this->menu = recursiveTwo($menu);
		$this->parentid = $parentid;

		if(IS_POST && I("addMenu")){
			$rules = array(
				array('title','require',-1), //菜单名称不能为空
				array('name','require',-2), //菜单规则不能为空
				array('title','',-3,0,'unique',1), //菜单名称唯一性
				array('name','',-4,0,'unique',1), //菜单规则唯一性
			);
			$table_AuthRule = M("AuthRule");
			if($table_AuthRule->validate($rules)->create()){
				if($id = $table_AuthRule->add())
				{
					$this->ajaxReturn(-20);
				}
			}
			else
			{
				$this->ajaxReturn($table_AuthRule->getError());
			}

		}
		$this->display();
	}
	// 修改菜单
	public function editMenu()
	{
		$id = I('id');
		$rule = M('AuthRule')->where(array('id'=>$id))->find();
		if(S('AuthMenu')){
			$menu = S('AuthMenu');
		}else{
			$menu = M('AuthRule')->select();
			S('AuthMenu',$menu,C('AUTH_MENU_TIME'));
		}

		$this->menu = recursiveTwo($menu);
		// p($this->menu);
		$this->rule = $rule;

		if(IS_POST && I("editMenu")){
			$rules = array(
				array('title','require',-1), //菜单名称不能为空
				array('name','require',-2), //菜单规则不能为空
				array('title','',-3,0,'unique',1), //菜单名称唯一性
				array('name','',-4,0,'unique',1), //菜单规则唯一性
			);
			$table_AuthRule = M("AuthRule");
			if($table_AuthRule->validate($rules)->create()){
				if($id = $table_AuthRule->save())
				{
					$this->ajaxReturn(-20);
				}
			}
			else
			{
				$this->ajaxReturn($table_AuthRule->getError());
			}

		}
		$this->display();
	}
	// 删除菜单
	public function delMenu()
	{
		if(IS_POST && I('id')){
			// $status = M("AuthRule")->delete(I('id'));
			// $msg = doReturn("数据成功删除","数据删除失败，请联系管理员",$status);
			// $this->ajaxReturn($msg);
			// exit;
			$id = I('id');
			$db = M('AuthRule');
			$cateid = $db->field(array('id','pid'))->select();
			$delid = get_all_child($cateid,$id);

			$delid[] = $id;
			$where = array('id' => array('IN',$delid));
			$status = $db->where($where)->delete();
			$msg = returnMsg("菜单删除成功","菜单删除失败",$status);
			$this->ajaxReturn($msg);
			exit;
		}
	}
	// 菜单排序
	public function sortMenu(){
		$error_id = "";
		$status = true;
		$sortRule = I("sort");
		foreach($sortRule as $k => $v){
			$data = array(
				"id"=>$k,
				"sort"=>$v
			);
			$status = M("AuthRule")->save($data);
			if ($status === false){
				$error_id = $k;
				break;//当排序失败时，捕获错误ID，结束程序
			}
		}
		$msg = returnMsg("菜单排序成功","<br />发生错误的排序ID：$error_id",$status);
		$this->ajaxReturn($msg);
	}
	//管理员管理
	public function user()
	{
		$count = D('UserRelation')->count();
		$Page  = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
		$Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('first','第一页');
        $Page->setConfig('last','最后一页');
        $User = D('UserRelation')->relation(true)->order('uid asc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $show = $Page->show();// 分页显示输出
        $this->assign("Userlist", $User);
        $this->assign("page", $show);
		$this->display();
		// p($User);
	}
	//查看权限
	public function showRole()
	{
		if(I('id') == '1'){
			echo "不允许对超级管理员授权";
			exit;
		}
		// $authrule = M('AuthRule');
		// $list = $authrule->order('sort')->select();
		// //降数组以树形排列，分三层
		// $this->node = listToTree($list);
		// $this->display();
		if(IS_POST && I('setRole') == 'setRole'){
			// $RuleIds = implode(",",array_unique(explode(',',I('setRoleRule'))));
			$data = array(
				'id' => I('id','0','int'),
				'rules' => I('menuid')
			);
			$status = M("AuthGroup")->save($data);
			$msg = returnMsg("授权权限成功","授权权限失败",$status);
			$this->ajaxReturn($msg);
			exit;
		}
		//加载角色节点权限数据
		// if(IS_POST){
			$table_AuthRule = M("AuthRule")->field("id,title as name,pid,icon as cc")->select();
			foreach($table_AuthRule as $k3 => $v3)
	        {
	            $table_AuthRule[$k3]['iconSkin'] = 'tree-icon '.$v3['cc'].' ';
	        }
			$table_AuthGroup = M("AuthGroup")->find(I('id'));
			$RuleIds = explode(",",$table_AuthGroup['rules']);
			$data = treeRule($table_AuthRule);
			$data = treeState($data,$RuleIds);
			// $this->ajaxReturn($data);
		// }
		// p($data);
		$this->assign('json', json_encode($data));

		$this->id = I('id');
		$this->name = I('data');
		$this->display();
	}
	//添加管理员
	public function addUser()
	{
		$this->role = M('AuthGroup')->field('id,title')->order('sort asc')->select();
		if(IS_POST && I("addUser"))
		{
			$rules = array(
	        // array('verify','require',-2),
	        //-1,账号以字母开头,5-17 字母、数字、下划线'_'
	        array('username','/^[a-zA-Z][\w]{4,16}$/',-2,0),
	        //-4,账号被占用
	        array('username', '', -3, 0, 'unique', 1),
	        //-1,昵称必须是中文
	        array('nickname','/^[\x{4e00}-\x{9fa5}]+$/u',-4,0),//
	        //-4,昵称被占用
	        array('nickname', '', -5, 0, 'unique', 1),
	        //密码以字母开头,8-17 字母、数字、下划线'_'
	        array('password','/^[a-zA-Z][\w]{7,16}$/',-6,0),
	        // 验证确认密码是否和密码一致
	        array('passworded','password',-7,0,'confirm'),
	        //-6,QQ不合法！
	        // array('qq','/^[1-9]\d{4,9}$/',-8,0),
	        //-3,邮箱格式不正确
	        array('email','email',-9,0),
	        //-6,手机号不合法！
	        // array('phone','/(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0-9])[0-9]{8}$/',-10,0),
	        //-5,QQ被占用
	        // array('qq','',-11,0,'unique',1),
	        //-5,邮箱被占用
	        array('email','',-12,0,'unique',1),
	        //-7,手机号被占用
	        // array('phone','',-13,0,'unique',1),

	        );
	        $table_User = D("UserRelation");
	        if($table_User->validate($rules)->create()){
	        	$table_User->password = jiami(I('password'));
				$table_User->usergroup = I('role_id');
				$table_User->create_time = time();
				$table_User->create_ip = get_client_ip();
				if($status = $table_User->relation(true)->add())
				{
					$this->ajaxReturn(-20);
				}
				else
				{
					$this->ajaxReturn(-21);
				}

			}
			else
			{
				$this->ajaxReturn($table_User->getError());
			}
		}
		$this->display();
	}
	// 修改管理员
	public function editUser()
	{
		if(I('id') == '1'){
			echo "不允许对超级管理员进行修改";
			exit;
		}
		$this->role = M('AuthGroup')->field('id,title')->order('sort asc')->select();
		if(IS_POST && I("editUser"))
		{
			$rules = array(
	        // array('verify','require',-2),
	        //-1,账号以字母开头,5-17 字母、数字、下划线'_'
	        array('username','/^[a-zA-Z][\w]{4,16}$/',-2,0),
	        //-4,账号被占用
	        array('username', '', -3, 0, 'unique', 1),
	        //-1,昵称必须是中文
	        array('nickname','/^[\x{4e00}-\x{9fa5}]+$/u',-4,0),//
	        //-4,昵称被占用
	        array('nickname', '', -5, 0, 'unique', 1),
	        //密码以字母开头,8-17 字母、数字、下划线'_'
	        // array('password','/^[a-zA-Z][\w]{7,16}$/',-6,0),
	        // 验证确认密码是否和密码一致
	        array('passworded','password',-7,0,'confirm'),
	        //-6,QQ不合法！
	        // array('qq','/^[1-9]\d{4,9}$/',-8,0),
	        //-3,邮箱格式不正确
	        array('email','email',-9,0),
	        //-6,手机号不合法！
	        // array('phone','/(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0-9])[0-9]{8}$/',-10,0),
	        //-5,QQ被占用
	        // array('qq','',-11,0,'unique',1),
	        //-5,邮箱被占用
	        array('email','',-12,0,'unique',1),
	        //-7,手机号被占用
	        // array('phone','',-13,0,'unique',1),

	        );
	        $table_User = D("UserRelation");
	        if($table_User->validate($rules)->create()){
	        	if(I('password') == '' || I('passworded') == ''){//当没有修改密码时
					unset($table_User->password);
				}
				else
				{
					$table_User->password = jiami(I('password'));
				}
				$table_User->usergroup = I('role_id');
				// $table_User->create_time = time();
				// $table_User->createip = get_client_ip();
				if($status = $table_User->relation(true)->save())
				{
					$this->ajaxReturn(-20);
				}
				else
				{
					$this->ajaxReturn(-21);
				}

			}
			else
			{
				$this->ajaxReturn($table_User->getError());
			}
		}
		$user = D("UserRelation")->relation(true)->find(I('id'));
		$this->user = $user;
		// p($user);
		$this->display();
	}
	//删除单个管理员
	public function delUser(){
		if(I('id') == '1'){
			$msg = returnMsg("","不允许删除原始超级管理员",false);
			$this->ajaxReturn($msg);
			exit;
		}
		if(IS_POST && I('id')){
			$status = D("UserRelation")->relation(true)->delete(I('id'));
			$msg = returnMsg("删除用户成功","删除用户失败，请联系管理员",$status);
			$this->ajaxReturn($msg);
			exit;
		}
	}
	//角色管理
	public function role()
	{
		$count = M('AuthGroup')->count();
		$Page  = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
		$Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('first','第一页');
        $Page->setConfig('last','最后一页');
        $User = M('AuthGroup')->order('id asc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $show = $Page->show();// 分页显示输出
        $this->assign("Userlist", $User);
        $this->assign("page", $show);
		$this->display();
	}
	//角色权限设置
	public function setRole()
	{

		if(I('id') == '1'){
			echo "不允许对超级管理员授权";
			exit;
		}
		// $authrule = M('AuthRule');
		// $list = $authrule->order('sort')->select();
		// //降数组以树形排列，分三层
		// $this->node = listToTree($list);
		// $this->display();
		if(IS_POST && I('setRole') == 'setRole'){
			// $RuleIds = implode(",",array_unique(explode(',',I('setRoleRule'))));
			$data = array(
				'id' => I('id','0','int'),
				'rules' => I('menuid')
			);
			$status = M("AuthGroup")->save($data);
			$msg = returnMsg("授权权限成功","授权权限失败",$status);
			$this->ajaxReturn($msg);
			exit;
		}
		//加载角色节点权限数据
		// if(IS_POST){
			$table_AuthRule = M("AuthRule")->field("id,title as name,pid,icon as cc")->select();
			foreach($table_AuthRule as $k3 => $v3)
	        {
	            $table_AuthRule[$k3]['iconSkin'] = 'tree-icon '.$v3['cc'].' ';
	        }
			$table_AuthGroup = M("AuthGroup")->find(I('id'));
			$RuleIds = explode(",",$table_AuthGroup['rules']);
			$data = treeRule($table_AuthRule);
			$data = treeState($data,$RuleIds);
			// $this->ajaxReturn($data);
		// }
		// p($data);
		$this->assign('json', json_encode($data));

		$this->id = I('id');
		$this->name = I('data');
		$this->display();
	}
	//添加角色
	public function addRole()
	{
		if(IS_POST && I("addRole"))
		{
			$rules = array(
	        //-4,角色名称被占用
	        array('title', '', -3, 0, 'unique', 1),
	        //-1,角色名称必须是中文
	        array('title','/^[\x{4e00}-\x{9fa5}]+$/u',-4,0),
	        );
	        $table_Group = M("AuthGroup");
	        if($table_Group->validate($rules)->create()){
				if($status = $table_Group->add())
				{
					$this->ajaxReturn(-20);
				}
				else
				{
					$this->ajaxReturn(-21);
				}

			}
			else
			{
				$this->ajaxReturn($table_Group->getError());
			}
		}
		$this->display();
	}
	//编辑角色
	public function editRole()
	{
		if(IS_POST && I("editRole"))
		{
			$rules = array(
	        //-4,角色名称被占用
	        array('title', '', -3, 0, 'unique', 1),
	        //-1,角色名称必须是中文
	        array('title','/^[\x{4e00}-\x{9fa5}]+$/u',-4,0),
	        );
	        $table_Group = M("AuthGroup");
	        if($table_Group->validate($rules)->create()){
				if($status = $table_Group->save())
				{
					$this->ajaxReturn(-20);
				}
				else
				{
					$this->ajaxReturn(-21);
				}

			}
			else
			{
				$this->ajaxReturn($table_Group->getError());
			}
		}
		$this->role = M("AuthGroup")->where(array('id'=>I('id')))->find();
		$this->display();
	}
	//删除单个角色
	public function delRole(){
		if(I('id') == '1'){
			$msg = returnMsg("","不允许删除原始超级管理员角色",false);
			$this->ajaxReturn($msg);
			exit;
		}
		if(IS_POST && I('id')){
			$status = M("AuthGroup")->delete(I('id'));
			$msg = returnMsg("删除角色成功","删除角色失败，请联系管理员",$status);
			$this->ajaxReturn($msg);
			exit;
		}
	}
	// 站点配置
	public function config()
	{
		// $this->Site = include APP_PATH . '/Common/Conf/siteset.config.php';
		// p($config);
		// echo APP_PATH;
		$this->display();
	}
	//修改配置文件
	public function setconfig()
	{
		if(IS_POST && I('setconfig'))
		{
			$file = APP_PATH . '/Common/Conf/siteset.config.php';
			$config = array_merge(include $file, array_change_key_case($_POST, CASE_UPPER));
			$str = "<?php\r\nreturn " . var_export($config, true) . ";\r\n?>";
			if (file_put_contents($file, $str)) {
				$status = true;
				$msg = returnMsg("修改配置成功","修改配置失败",$status);
			} else {
				$status = false;
				$msg = returnMsg("修改配置成功","修改配置失败",$status);
			}
			$this->ajaxReturn($msg);
		}
	}
	//登录日志
	public function loginLog()
	{
		$where = array();
        $username = I('username');
        $start_time = I('start_time');
        $end_time = I('end_time');
        $loginip = I('loginip');
        $status = I('status');
        if (!empty($username)) {
            $where['username'] = array('like', '%' . $username . '%');
        }
        if (!empty($start_time) && !empty($end_time)) {
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time) + 86399;
            $where['logintime'] = array(array('GT', $start_time), array('LT', $end_time), 'AND');
        }
        if (!empty($loginip)) {
            $where['loginip '] = array('like', "%{$loginip}%");
        }
        if ($status != '') {
            $where['status'] = $status;
        }
		$count = M('LoginLog')->where($where)->count();
		$Page  = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		// foreach($where as $key=>$val) {
		// 	$Page->parameter   .=   "$key=".urlencode($val).'&';
		// }
		$Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
		$Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('first','第一页');
        $Page->setConfig('last','最后一页');
        $logs = M('LoginLog')->where($where)->order('logintime desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $show = $Page->show();// 分页显示输出
        $this->assign("logslist", $logs);
        $this->assign("page", $show);
		$this->display();
	}
	// 删除上月登录日志
	public function delLoginLog()
	{
		$status = M('LoginLog')->where(array("logintime" => array("lt", time() - (86400 * 30))))->delete();
        $msg = returnMsg("删除登录日志成功！","删除登录日志失败！",$status);
		$this->ajaxReturn($msg);
		exit;
	}
	// 操作日志
	public function operateLog()
	{
		$where = array();
        $username = I('username');
        $start_time = I('start_time');
        $end_time = I('end_time');
        $ip = I('ip');
        $status = I('status');
        if (!empty($username)) {
            $where['username'] = array('like', '%' . $username . '%');
        }
        if (!empty($start_time) && !empty($end_time)) {
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time) + 86399;
            $where['time'] = array(array('GT', $start_time), array('LT', $end_time), 'AND');
        }
        if (!empty($ip)) {
            $where['ip '] = array('like', "%{$ip}%");
        }
        if ($status != '') {
            $where['status'] = $status;
        }
		$count = M('OperateLog')->where($where)->count();
		$Page  = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		// foreach($where as $key=>$val) {
		// 	$Page->parameter   .=   "$key=".urlencode($val).'&';
		// }
		$Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
		$Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('first','第一页');
        $Page->setConfig('last','最后一页');
        $logs = M('OperateLog')->where($where)->order('time desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $show = $Page->show();// 分页显示输出
        $this->assign("logslist", $logs);
        $this->assign("page", $show);
		$this->display();
		// $this->display();
	}
	// 删除上月操作日志
	public function delOperateLog()
	{
		$status = M('OperateLog')->where(array("time" => array("lt", time() - (86400 * 30))))->delete();
    	$msg = returnMsg("删除操作日志成功！","删除操作日志失败！",$status);
		$this->ajaxReturn($msg);
		exit;
	}
	//数据备份
	public function database($type = null){
		switch ($type) {
			/* 数据备份 */
            case 'export':
            	$Db = \Think\Db::getInstance();
				$list  = $Db->query('SHOW TABLE STATUS');
				$list  = array_map('array_change_key_case', $list);
				foreach ($list as $k => $v) {
		            $list[$k]['size'] = format_size($v['data_length'] + $v['Index_length']);
		            $total+=$v['data_length'] + $v['Index_length'];
		        }
				$count = count($list);
				$this->assign("lists", $list);
				$this->assign("total", format_size($total));
		        $this->assign("tables", $count);
		        break;
		    /* 数据还原 */
            case 'import':
            	//列出备份文件列表
                $path = C('DATA_BACKUP_PATH');
                if(!is_dir($path)){
                    mkdir($path, 0755, true);
                }
                $path = realpath($path);
                $flag = \FilesystemIterator::KEY_AS_FILENAME;
                $glob = new \FilesystemIterator($path,  $flag);

                $list = array();
                foreach ($glob as $name => $file) {
                    if(preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql(?:\.gz)?$/', $name)){
                        $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');

                        $date = "{$name[0]}-{$name[1]}-{$name[2]}";
                        $time = "{$name[3]}:{$name[4]}:{$name[5]}";
                        $part = $name[6];

                        if(isset($list["{$date} {$time}"])){
                            $info = $list["{$date} {$time}"];
                            $info['part'] = max($info['part'], $part);
                            $info['size'] = $info['size'] + $file->getSize();
                        } else {
                            $info['part'] = $part;
                            $info['size'] = $file->getSize();
                        }
                        $extension        = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
                        $info['compress'] = ($extension === 'SQL') ? '-' : $extension;
                        $info['time']     = strtotime("{$date} {$time}");

                        $list["{$date} {$time}"] = $info;
                    }
                }
                $this->assign('lists', $list);
                break;
            default:
                $this->error('参数错误！');
		}
        $this->display($type);
	}
	/**
     * 优化表
     * @param  String $tables 表名
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function optimize($tables = null){
        if($tables) {
            $Db   = Db::getInstance();
            if(is_array($tables)){
                $tables = implode('`,`', $tables);
                $list = $Db->query("OPTIMIZE TABLE `{$tables}`");

                if($list){
                    $this->success("数据表优化完成！");
                } else {
                    $this->error("数据表优化出错请重试！");
                }
            } else {
                $list = $Db->query("OPTIMIZE TABLE `{$tables}`");
                if($list){
                    $this->success("数据表'{$tables}'优化完成！");
                } else {
                    $this->error("数据表'{$tables}'优化出错请重试！");
                }
            }
        } else {
            $this->error("请指定要优化的表！");
        }
    }

    /**
     * 修复表
     * @param  String $tables 表名
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function repair($tables = null){
        if($tables) {
            $Db   = Db::getInstance();
            if(is_array($tables)){
                $tables = implode('`,`', $tables);
                $list = $Db->query("REPAIR TABLE `{$tables}`");

                if($list){
                    $this->success("数据表修复完成！");
                } else {
                    $this->error("数据表修复出错请重试！");
                }
            } else {
                $list = $Db->query("REPAIR TABLE `{$tables}`");
                if($list){
                    $this->success("数据表'{$tables}'修复完成！");
                } else {
                    $this->error("数据表'{$tables}'修复出错请重试！");
                }
            }
        } else {
            $this->error("请指定要修复的表！");
        }
    }
    //清除正在执行的备份任务
	public function delBackupLock()
	{
		unlink(C('DATA_BACKUP_PATH') . 'backup.lock');
		$this->success('清除正在执行的备份任务成功！');
	}
    /**
     * 删除备份文件
     * @param  Integer $time 备份时间
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function delData($time = 0){
        if($time){
            $name  = date('Ymd-His', $time) . '-*.sql*';
            $path  = realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR . $name;
            array_map("unlink", glob($path));
            if(count(glob($path))){
                $this->error('备份文件删除失败，请检查权限！');
            } else {
                $this->success('备份文件删除成功！');
            }
        } else {
            $this->error('参数错误！');
        }
    }
	/**
     * 备份数据库
     * @param  String  $tables 表名
     * @param  Integer $id     表ID
     * @param  Integer $start  起始行数
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function export($tables = null, $id = null, $start = null){
        if(IS_POST && !empty($tables) && is_array($tables)){ //初始化
            $path = C('DATA_BACKUP_PATH');
            if(!is_dir($path)){
                mkdir($path, 0755, true);
            }
            //读取备份配置
            $config = array(
                'path'     => realpath($path) . DIRECTORY_SEPARATOR,
                'part'     => C('DATA_BACKUP_PART_SIZE'),
                'compress' => C('DATA_BACKUP_COMPRESS'),
                'level'    => C('DATA_BACKUP_COMPRESS_LEVEL'),
            );

            //检查是否有正在执行的任务
            $lock = "{$config['path']}backup.lock";
            if(is_file($lock)){
                $this->error('检测到有一个备份任务正在执行，请稍后再试！');
            } else {
                //创建锁文件
                file_put_contents($lock, NOW_TIME);
            }

            //检查备份目录是否可写
            is_writeable($config['path']) || $this->error('备份目录不存在或不可写，请检查后重试！');
            session('backup_config', $config);

            //生成备份文件信息
            $file = array(
                'name' => date('Ymd-His', NOW_TIME),
                'part' => 1,
            );
            session('backup_file', $file);

            //缓存要备份的表
            session('backup_tables', $tables);

            //创建备份文件
            $Database = new Database($file, $config);
            if(false !== $Database->create()){
                $tab = array('id' => 0, 'start' => 0);
                $this->success('初始化成功！', '', array('tables' => $tables, 'tab' => $tab));
            } else {
                $this->error('初始化失败，备份文件创建失败！');
            }
        } elseif (IS_GET && is_numeric($id) && is_numeric($start)) { //备份数据
            $tables = session('backup_tables');
            //备份指定表
            $Database = new Database(session('backup_file'), session('backup_config'));
            $start  = $Database->backup($tables[$id], $start);
            if(false === $start){ //出错
                $this->error('备份出错！');
            } elseif (0 === $start) { //下一表
                if(isset($tables[++$id])){
                    $tab = array('id' => $id, 'start' => 0);
                    $this->success('备份完成！', '', array('tab' => $tab));
                } else { //备份完成，清空缓存
                    unlink(session('backup_config.path') . 'backup.lock');
                    session('backup_tables', null);
                    session('backup_file', null);
                    session('backup_config', null);
                    $this->success('备份完成！');
                }
            } else {
                $tab  = array('id' => $id, 'start' => $start[0]);
                $rate = floor(100 * ($start[0] / $start[1]));
                $this->success("正在备份...({$rate}%)", '', array('tab' => $tab));
            }

        } else { //出错
            $this->error('参数错误！');
        }
    }
    /**
     * 还原数据库
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function import($time = 0, $part = null, $start = null){
        if(is_numeric($time) && is_null($part) && is_null($start)){ //初始化
            //获取备份文件信息
            $name  = date('Ymd-His', $time) . '-*.sql*';
            $path  = realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR . $name;
            $files = glob($path);
            $list  = array();
            foreach($files as $name){
                $basename = basename($name);
                $match    = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
                $gz       = preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql.gz$/', $basename);
                $list[$match[6]] = array($match[6], $name, $gz);
            }
            ksort($list);

            //检测文件正确性
            $last = end($list);
            if(count($list) === $last[0]){
                session('backup_list', $list); //缓存备份列表
                $this->success('初始化完成！', '', array('part' => 1, 'start' => 0));
            } else {
                $this->error('备份文件可能已经损坏，请检查！');
            }
        } elseif(is_numeric($part) && is_numeric($start)) {
            $list  = session('backup_list');
            $db = new Database($list[$part], array(
                'path'     => realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR,
                'compress' => $list[$part][2]));

            $start = $db->import($start);

            if(false === $start){
                $this->error('还原数据出错！');
            } elseif(0 === $start) { //下一卷
                if(isset($list[++$part])){
                    $data = array('part' => $part, 'start' => 0);
                    $this->success("正在还原...#{$part}", '', $data);
                } else {
                    session('backup_list', null);
                    $this->success('还原完成！');
                }
            } else {
                $data = array('part' => $part, 'start' => $start[0]);
                if($start[1]){
                    $rate = floor(100 * ($start[0] / $start[1]));
                    $this->success("正在还原...#{$part} ({$rate}%)", '', $data);
                } else {
                    $data['gz'] = 1;
                    $this->success("正在还原...#{$part}", '', $data);
                }
            }

        } else {
            $this->error('参数错误！');
        }
    }
    public function sendEmail($time){
    	if($time){
    		$subject = '你好，下面是数据备份文件';
            $name  = date('Ymd-His', $time) . '-*.sql*';
            $path  = realpath(C('DATA_BACKUP_PATH')) . DIRECTORY_SEPARATOR . $name;
            $forpath = glob($path);
            foreach($forpath as $k => $v)
            {
            	\Intendant\Model\EmailModel::sendEmail('河马叔叔','8192332@qq.com','',$v,$subject);
            }
        } else {
            $this->error('参数错误！');
        }
    }
    //zip打包图片文件和文件
    public function zipFileBackup()
    {
    	$time = time();
    	$filename=  C('FILE_BACKUP_PATH') .'/' . date("Ymd-His",time()) .'.zip'; //最终生成的文件名（含路径）
		if(file_exists($filename)){
		    unlink($filename);
		}
		$zip=new \ZipArchive();
		if($zip->open($filename,\ZIPARCHIVE::CREATE)!==TRUE){
		    $this->ajaxReturn(array(
				'status' => 1,
				'info' => '无法打开文件，或者文件创建失败',
			));
		}
		addFileToZip('Uploads/',$zip)	;
		$zip->close();//关闭
		$time = time() - $time;
		if(!file_exists($filename)){
		    $this->ajaxReturn(array(
				'status' => 1,
				'info' => '无法找到文件',
			));
		}
		else
		{
			$this->ajaxReturn(array(
				'status' => 1,
				'info' => "成功备份文件与图片。耗时：{$time} 秒",
				'url' => U('SysData/imgFileList'),
			));
		}
    }
    //列出以打包文件与图片的压缩包
    public function fileBackup()
    {
    	$data = getFileBackupList();
        $this->assign("lists", $data['list']);
        $this->assign("total", $data['size']);
        $this->assign("files", count($data['list']));
		$this->display();
    }
    //删除已备份的文件ZIP
    public function delFileBackup() {
        if(!IS_AJAX) E('页面不存在');
        $time = time();
        $file = I('file');
        if (empty($file) || count($file) == 0)
        {
        	$this->ajaxReturn(array(
				'status' => 0,
				'info' => "请先选择要删除的文件",
			));die;
        }
        delDirAndFile(C('FILE_BACKUP_PATH') . $file);
        $time = time() - $time;
        $this->ajaxReturn(array(
			'status' => 1,
			'info' => "已删除：" . implode("、", $files) . "耗时：{$time} 秒",
			'url' => U('SysData/imgFileList'),
		));
    }
    //发送文件备份文件email
    public function sendFileZip($file = 0)
    {
        if($file){
        	$subject = '你好，下面是文件备份';
        	$path  = realpath(C('FILE_BACKUP_PATH')) . DIRECTORY_SEPARATOR . $file . '.zip';
            \Intendant\Model\EmailModel::sendEmail('河马叔叔','8192332@qq.com','',$path,$subject);
        } else {
            $this->error('参数错误！');
        }
    }

}
?>